package com.xiaojie.schedule;

import com.xiaojie.entity.User;
import com.xiaojie.lock.RedisDistributeLock;
import com.xiaojie.lock.RedisTemplateDistributeLock;
import com.xiaojie.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.UUID;

/**
 * @ClassMyTask
 * @Description 模拟定时任务
 * @AuthorAdministrator
 * @Date {Date}{Time}
 * @Version 1.0
 **/
@Component
public class MyRedisTemplateTask {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisDistributeLock  redisDistributeLock;
    private static final String REDISKEY = "xiaojie_redis_lock";
    private static final Long TIME_OUT=2L;
    //区别加锁和解锁的值一致，不会解别的锁
    private static final String value= UUID.randomUUID().toString();

    @Autowired
    private RedisTemplateDistributeLock redisTemplateDistributeLock;
     int i;
    @Scheduled(cron = "* * * 5 * ? ")
    public void scheduledTask(){
        if(!redisTemplateDistributeLock.getLock(REDISKEY, value, TIME_OUT)){
            System.out.println("获取锁失败");
            return;
        };
        List<User> users = userMapper.selectAll();
        for (User user:users){
            user.setNum(user.getNum()+1);
            int updateNum = userMapper.updateNum(user.getNum(),user.getId());
            System.out.println(updateNum);
        }
        i++;
        System.out.println("执行了"+i+"次");
        //释放锁
        if( redisTemplateDistributeLock.releaseLock(REDISKEY, value)){
            System.out.println("释放锁成功。。。");
        }else{
            System.out.println("释放锁失败。。。。。");
        };
    }

}
